/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.prep.view.command;

import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ListIterator;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.commons.command.Command;
import br.ufmg.dees.insane.commons.view.ExtensionFileFilter;
import br.ufmg.dees.insane.model.prep.GeoPrepModel;
import br.ufmg.dees.insane.ui.rich.prep.view.DesktopPrep;
import br.ufmg.dees.insane.ui.rich.prep.view.InterfacePrep;

/**
 * This class is an implementation of the interface Command.
 * It's unabled to undo or redo.
 * Its "execute" opens a stored model calling
 * a file chooser to get the file.
 *
 * @author Ferreira, Reginaldo & Pitangueira, Roque
 * @since 13/11/2006
 * @see gui.command.AAAcommand
 */
public class OpenCommand implements Command {
    
    private DesktopPrep parent;
    private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter("isn", "INSANE-PREP Files");
    private boolean validFile;
	
//*****************************************************************************
	
    /**
     * Creates new OpenCommand
     * and sets the FileFilter do FileChooser.
     *
     * @param parent The JFrame parent.
     */
    public OpenCommand(JFrame parent) {
        this.parent = (DesktopPrep)parent;
        fileChooser.setFileFilter(filter);
    }
    
//*****************************************************************************
	
    /**
     * Calls the file chooser and opens a stored model.
     *
     * @see gui.command.AAAcommand#execute()
     */
    public void execute() {
    	
    		validFile = false;
			while (!validFile)
			{
				int retVal = fileChooser.showOpenDialog(parent);
				
				if (retVal == JFileChooser.APPROVE_OPTION)
				{
					//Checks if the file exists and is readable
					File file = fileChooser.getSelectedFile();
					if (file.exists() && file.isFile() && file.canRead())
					{
						validFile = true;
					}
					else
					{
						JOptionPane.showMessageDialog(parent, "File \"" + fileChooser.getSelectedFile().getPath() + "\" doesn't exist.", "Error Message", JOptionPane.ERROR_MESSAGE);
					}
				}
				else return;
			}
			
			Object objAux = new Object();
			try
			{
				ObjectInputStream stream = new ObjectInputStream(new FileInputStream(fileChooser.getSelectedFile()));
				objAux = stream.readObject();
				
				// Enable the menus
				this.parent.setInterface(true);
			}
			catch (Exception exc) 
			{
				Toolkit.getDefaultToolkit().beep();
				JOptionPane.showMessageDialog(parent, "Couldn't open file!", "Error Message", JOptionPane.ERROR_MESSAGE);
			}
			
			if(objAux instanceof GeoPrepModel)
			{
				GeoPrepModel mdl_opened;
				GeoPrepModel model_to_open = (GeoPrepModel)objAux;
				Boolean modelIsOpen = false;

				ListIterator it = parent.getModelList().listIterator();
			    while (it.hasNext())
			    {
			    	mdl_opened = (GeoPrepModel)it.next();
			    	if (model_to_open.getName().equals(mdl_opened.getName()) == true)
			    	{
			    		modelIsOpen = true;
			    	}
			    }
			    if (modelIsOpen == false)
			    {
			    	model_to_open.setName(fileChooser.getSelectedFile().getName().replaceAll(".isn",""));
			    	InterfacePrep intFrame = new InterfacePrep();
			    	intFrame.validate();
			    	intFrame.setModel(model_to_open);
			    	intFrame.setName("v1");
			    	intFrame.setTitle(model_to_open.getName() + " - " + intFrame.getName());

			    	parent.addInternalFrame(intFrame);
			    	intFrame.toFront();

			    	model_to_open.addObserver(intFrame);
			    	model_to_open.setIsModified(false);
			    	model_to_open.setHasFile(true);
			    	model_to_open.setPath(fileChooser.getSelectedFile().getPath());

			    	parent.addModelList(model_to_open);
			    	parent.nothingToUndo();
			    	parent.nothingToRedo();	
			    	parent.repaint();
			    	parent.getDesktopTextArea().addText("File open:  " + model_to_open.getPath());
			    }
			    else
			    {
			    	String message = "The file  [  " + model_to_open.getName() + "  ]  already is open.";
			    	parent.getDesktopTextArea().addText(message);
					JOptionPane.showMessageDialog(parent, message, "Information Message", JOptionPane.INFORMATION_MESSAGE);
			    }
			}
	}
            
//*****************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//*****************************************************************************
}//end of this class

